import os
import pytest
from fastapi.testclient import TestClient

from tldw_Server_API.app.main import app


@pytest.mark.integration
def test_abtest_export_idempotency(monkeypatch):
    # Disable admin-only for heavy evaluations and enable testing shortcut auth
    monkeypatch.setenv('EVALS_HEAVY_ADMIN_ONLY', 'false')
    monkeypatch.setenv('TESTING', 'true')

    client = TestClient(app)

    # Create minimal A/B test
    cfg = {
        "arms": [{"provider": "openai", "model": "text-embedding-3-small"}],
        "media_ids": [],
        "queries": [{"text": "hello"}],
        "retrieval": {"k": 1},
        "reuse_existing": True,
    }
    r = client.post("/api/v1/evaluations/embeddings/abtest", json={"name": "idem-exp", "config": cfg})
    assert r.status_code == 200
    tid = r.json()["test_id"]

    # Kick off a run (doesn't need to complete for export shape)
    r2 = client.post(f"/api/v1/evaluations/embeddings/abtest/{tid}/run", json={"config": cfg})
    assert r2.status_code == 200

    # Export with Idempotency-Key
    headers = {"Idempotency-Key": "abtest-export-1"}
    e1 = client.get(f"/api/v1/evaluations/embeddings/abtest/{tid}/export", params={"format": "json"}, headers=headers)
    assert e1.status_code == 200
    e2 = client.get(f"/api/v1/evaluations/embeddings/abtest/{tid}/export", params={"format": "json"}, headers=headers)
    assert e2.status_code == 200
    # The responses should be consistent for idempotent key (shape stable even if total may grow later)
    j1 = e1.json()
    j2 = e2.json()
    assert j1["test_id"] == tid and j2["test_id"] == tid
    assert isinstance(j1.get("total", 0), int) and isinstance(j2.get("total", 0), int)


@pytest.mark.integration
def test_abtest_delete_idempotency(monkeypatch):
    monkeypatch.setenv('EVALS_HEAVY_ADMIN_ONLY', 'false')
    monkeypatch.setenv('TESTING', 'true')
    client = TestClient(app)

    # Create minimal A/B test
    cfg = {
        "arms": [{"provider": "openai", "model": "text-embedding-3-small"}],
        "media_ids": [],
        "queries": [{"text": "hello"}],
        "retrieval": {"k": 1},
        "reuse_existing": True,
    }
    r = client.post("/api/v1/evaluations/embeddings/abtest", json={"name": "idem-del", "config": cfg})
    assert r.status_code == 200
    tid = r.json()["test_id"]

    headers = {"Idempotency-Key": "abtest-delete-1"}
    d1 = client.delete(f"/api/v1/evaluations/embeddings/abtest/{tid}", headers=headers)
    assert d1.status_code == 200
    d2 = client.delete(f"/api/v1/evaluations/embeddings/abtest/{tid}", headers=headers)
    assert d2.status_code == 200
    assert d1.json().get("status") == "deleted"
    assert d2.json().get("status") == "deleted"
